<?php

namespace app\common\model;

use app\common\validate\AdminUser as AdminValidate;
use app\common\validate\AdminUserUpdate as AdminValidateUpdate;
use think\Db;
use think\Model;

class AdminUser extends Model
{
    public $err_msg = '';

    public function login($username, $password)
    {
        $userInfo = Db::name("admin_user")->where(["username" => $username, 'status' => 1])->find();
        if (!$userInfo) {
            $this->err_msg = '用户状态无效或不存在！';
            return false;
        }
        if (!password_verify($password,$userInfo['password'])){
            $this->err_msg = '密码错误！';
            return false;
        }
        $this->saveSession($userInfo);
        return $userInfo;
    }


    public function saveSession($data)
    {
        $saveInfo = ['uid' => $data['id'], 'username' => $data['username']];
        session("user_session", $saveInfo);
    }


    //添加管理员
    public function add($data)
    {
        //对提交数据验证
        $validate = new AdminValidate;
        if ($validate->check($data)) {
            AdminUser::create([
                'username' => $data['username'],
                'password' => password_hash($data['password'],PASSWORD_DEFAULT),
                'status' => $data['status'],
                'group_id' => $data['group_id'],
                'create_time' => time(),
                'avatar' => './static/ace/assets/images/avatars/profile-pic.jpg'
            ]);
            return ['valid' => 1, 'msg' => '添加数据成功'];
        } else {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
    }


    public function edit($data)
    {
        $validate = new AdminValidateUpdate();
        if ($validate->check($data)) {
            AdminUser::where('id', $data['user_id'])
                ->update([
                    'username' => $data['username'],
                    'password' => password_hash($data['password'],PASSWORD_DEFAULT),
                    'status' => $data['status'],
                    'update_time' => time(),
                    'group_id' => $data['group_id']
                ]);
            return ['valid' => 1, 'msg' => '数据修改成功'];
        } else {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
    }


}